package com.zlict.admin.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.hutool.core.util.ObjectUtil;
import com.zlict.admin.domain.*;
import com.zlict.admin.mapper.RdAssetsAmortizationDetailMapper;
import com.zlict.common.exception.ServiceException;
import com.zlict.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.zlict.admin.mapper.RdIntangibleAssetsMapper;
import com.zlict.admin.domain.RdIntangibleAssets;
import com.zlict.admin.service.IRdIntangibleAssetsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资产管理-无形资产Service业务层处理
 * 
 * @author lqh
 * @date 2025-06-11
 */
@Service
@RequiredArgsConstructor
public class RdIntangibleAssetsServiceImpl implements IRdIntangibleAssetsService
{
    private static final String ADD_TYPE = "1"; // 新增
    private static final String UPDATE_TYPE = "2";
    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(RdIntangibleAssetsServiceImpl.class);
    private final RdIntangibleAssetsMapper rdIntangibleAssetsMapper;
    private final RdAssetsAmortizationDetailMapper rdAssetsAmortizationDetailMapper;

    /**
     * 查询资产管理-无形资产
     * 
     * @param id 资产管理-无形资产主键
     * @return 资产管理-无形资产
     */
    @Override
    public RdIntangibleAssets selectRdIntangibleAssetsById(Long id)
    {
        return rdIntangibleAssetsMapper.selectRdIntangibleAssetsById(id);
    }

    /**
     * 查询资产管理-无形资产列表
     * 
     * @param rdIntangibleAssets 资产管理-无形资产
     * @return 资产管理-无形资产
     */
    @Override
    public List<RdIntangibleAssets> selectRdIntangibleAssetsList(RdIntangibleAssets rdIntangibleAssets)
    {
        return rdIntangibleAssetsMapper.selectRdIntangibleAssetsList(rdIntangibleAssets);
    }

    /**
     * 新增资产管理-无形资产
     * 
     * @param rdIntangibleAssets 资产管理-无形资产
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRdIntangibleAssets(RdIntangibleAssets rdIntangibleAssets)
    {
        rdIntangibleAssets.setCreateTime(DateUtils.getNowDate());
        int i = rdIntangibleAssetsMapper.insertRdIntangibleAssets(rdIntangibleAssets);
        //添加折旧明细
        return addCostDetail(rdIntangibleAssets, i, ADD_TYPE);
    }

    /**
     * 修改资产管理-无形资产
     * 
     * @param rdIntangibleAssets 资产管理-无形资产
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRdIntangibleAssets(RdIntangibleAssets rdIntangibleAssets)
    {
        rdIntangibleAssets.setUpdateTime(DateUtils.getNowDate());
        int i =  rdIntangibleAssetsMapper.updateRdIntangibleAssets(rdIntangibleAssets);
        //添加折旧明细
        return addCostDetail(rdIntangibleAssets, i, UPDATE_TYPE);
    }

    /**
     * 添加折旧明细
     */
    @Transactional(rollbackFor = Exception.class)
    public int addCostDetail(RdIntangibleAssets rdIntangibleAssets, int i, String updateType) {
        try {
            int months = Integer.parseInt(rdIntangibleAssets.getAmortizationMonth());
            // 执行核心逻辑并记录上下文信息
            int a = batchCreateDepreciationDetails(
                    rdIntangibleAssets.getId(),
                    months,
                    rdIntangibleAssets.getDevalue(),
                    String.valueOf(rdIntangibleAssets.getStartAmortizeTime()),
                    null,
                    updateType
            );
            if (a <= 0) {
                LOGGER.warn("折旧明细创建失败, 资产ID: {}, 时间: {}",
                        rdIntangibleAssets.getId(), rdIntangibleAssets.getStartAmortizeTime());
                throw new ServiceException("折旧明细添加失败");
            }
        } catch (NumberFormatException e) {
            LOGGER.error("参数转换异常, 资产ID: {}, 错误详情: {}",
                    rdIntangibleAssets.getId(), e.getMessage(), e);
            throw new ServiceException("购买类型格式错误");
        } catch (Exception e) {
            // 参数化日志
            LOGGER.error("未知异常发生在折旧明细创建过程中, 资产ID: {}, 错误详情: {}", rdIntangibleAssets.getId(), e.getMessage(), e);
            throw new ServiceException("系统内部错误：" + e.getMessage());
        }
        return i;
    }

    /**
     * 批量生成折旧明细
     */
    @Transactional(rollbackFor = Exception.class) // 补充rollbackFor
    public int batchCreateDepreciationDetails(Long intangibleId,  Integer months,BigDecimal monthlyAmount,
                                              String startDateStr, Long userId, String addType) {
        if ("2".equals(addType)) {
            //根据资产id删除原有明细
            rdAssetsAmortizationDetailMapper.deleteRdAssetsAmortizationDetailById(intangibleId);
        }
        List<RdAssetsAmortizationDetail> details = new ArrayList<>();

        // 使用 DateTimeFormatter 定义对应的日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);

        // 使用定义好的格式和本地化信息进行解析
        LocalDate startDate =  LocalDate.parse(startDateStr, formatter);


        Date currentTime = new Date();

        for (int i = 0; i < months; i++) {
            LocalDate currentMonth = startDate.plusMonths(i);
            YearMonth yearMonth = YearMonth.from(currentMonth);
            RdAssetsAmortizationDetail detail = new RdAssetsAmortizationDetail();
            detail.setIntangibleId(intangibleId);
            detail.setCostTime(java.sql.Date.valueOf(yearMonth.atDay(1)));
            detail.setCostAmount(monthlyAmount);
            detail.setCostStartDay("1");
            detail.setCostEndDay(String.valueOf(yearMonth.lengthOfMonth()));
            detail.setCostRule(String.format("本月1日-本月%d日", yearMonth.lengthOfMonth()));
            detail.setUpdateTime(currentTime);
            detail.setCreateBy(userId);
            detail.setCreateTime(currentTime);
            detail.setUpdateBy(userId);
            details.add(detail);
        }
        // 批量新增明细
        return rdAssetsAmortizationDetailMapper.batchInsertRdAssetsAmortizationDetail(details);
    }

    /**
     * 批量删除资产管理-无形资产(逻辑删除)
     * 
     * @param ids 需要删除的资产管理-无形资产主键
     * @return 结果
     */
    @Override
    public int deleteRdIntangibleAssetsByIds(Long[] ids)
    {
        return rdIntangibleAssetsMapper.batchUpdate(ids);
    }

    /**
     * 查询资产管理-无形资产摊销明细
     *
     * @param id 资产管理-无形资产主键
     * @return 资产管理-无形资产
     */
    @Override
    public RdIntangibleAssets selectRdAssetsAmortizationDetailById(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("参数错误");
        }
        // 查询固定资产信息
        RdIntangibleAssets rs = new RdIntangibleAssets();
        rs.setId(id);
        RdIntangibleAssets rdIntangibleAssets = rdIntangibleAssetsMapper.selectRdIntangibleAssetsDetailById(rs);
        if(ObjectUtil.isNotEmpty(rdIntangibleAssets)){
            //获取资产详情
            RdAssetsAmortizationDetail rdAssetsAmortizationDetail = new RdAssetsAmortizationDetail();
            rdAssetsAmortizationDetail.setIntangibleId(id);
            List<RdAssetsAmortizationDetail> list = rdAssetsAmortizationDetailMapper.selectRdAssetsAmortizationDetailList(rdAssetsAmortizationDetail);
            //设置资产详情列表
            if(ObjectUtil.isNotEmpty(list)){
                rdIntangibleAssets.setRdAssetsAmortizationDetails(list);
            }
        }
        return rdIntangibleAssets;
    }

    @Override
    public int batchEnable(Long[] ids) {
        if (ObjectUtil.isEmpty(ids)) {
            throw new RuntimeException("参数错误");
        }
        return rdIntangibleAssetsMapper.batchEnable(ids);
    }

    @Override
    public int batchDisable(Long[] ids) {
        if (ObjectUtil.isEmpty(ids)) {
            throw new RuntimeException("参数错误");
        }
        return rdIntangibleAssetsMapper.batchDisable(ids);
    }
}
